<template>
  <view>
    <view class="w100  pl-30 pr-30">
      <view class="rows rowsm w100" style="justify-content: space-between;">
        <view class="rows rowsm" style="width: 70%;">
          <view class="fs-28 fw-b col000 mr-16 overFlow" v-if="classItem">
            {{ classItem }}
          </view>
          <view class="fs-28 col000 mr-16 p-all-16" :class="{ 'fw-b': !classItem }" v-else
            @click="classItem = null, handelType()">
            全部
          </view>

          <view class="rows rowsm" @click="showPicker" style="white-space: nowrap;">
            <view class="fs-26 col666 mr-4">切换班级</view>
            <image src="/static/icon_1jt.png" class="w-20 h-20" mode=""></image>
          </view>
          <view class="rows rowsm" @click="classItem = null, handelReset()" style="white-space: nowrap;">
            <view class="fs-26 col666 mr-4">重置</view>
          </view>
        </view>

        <view class="add mb-10 mt-20" @click="addTask"
          v-if="permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:task:add')">+新增任务</view>
      </view>
      <view class="w100">
        <uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" />
      </view>
      <!-- 搜索部分 -->
      <view class="w100 bgff mt-10 mb-10 pl-20 pr-20 pt-10 pb-10 br-20">
        <!-- 实践课程 -->
        <view class="rowsb rowsm mb-10">
          <!-- <view class="title" style="width:20%;">实践课程：</view> -->
          <!-- <scroll-view scroll-x="true" style="white-space: nowrap;"> -->
            <view class="rows rowsm h100" style="flex-wrap: wrap;">
              <view class="pl-20 pr-20 h-52 rowsc rowsm br-26 fs-26 mr-20 mt-10 mb-10" v-for="(item, index) in practiceType"
                :key="index"
                :style="active3 == practiceType[index].value ? 'color: #fff;background: linear-gradient(to bottom,#4897FF,#4878FF);' : 'background-color: #F4F4F4;color: #666;'"
                @click="handelPracticeType(index)">{{ item.name }}</view>
            </view>
          <!-- </scroll-view> -->
        </view>
        <!--任务状态：  -->
        <view class="rowsb rowsm mb-20 mt-10">
          <!-- <view class="title" style="width:20%;">任务状态：</view> -->
          <scroll-view scroll-x="true" style="white-space: nowrap;">
            <view class="rows rowsm h100">
              <view class="pl-20 pr-20 h-52 rowsc rowsm br-26 fs-26 mr-20" v-for="(item, index) in taskTab" :key="index"
                :style="active == taskTab[index].value ? 'color: #fff;background: linear-gradient(to bottom,#4897FF,#4878FF);' : 'background-color: #F4F4F4;color: #666;'"
                @click="handelTab(index)">{{ item.name }}</view>
            </view>
          </scroll-view>
        </view>
        <view class="rowsb rowsm mb-20 mt-20">
          <view class="title" style="width:20%;">实践任务：</view>
          <u--input placeholder="请输入内容" border="surround" v-model="taskName" size="mini" @change="getList"></u--input>
          <!-- <uni-data-select style="flex: 1" v-model="taskName" :localdata="selectorList"></uni-data-select> -->
        </view>
        <view class="rows rowsm mb-20">
          <view class="title" style="width:20%;">发布时间：</view>
          <uni-datetime-picker v-model="range" type="daterange" @change="changeTime" />
        </view>
      </view>
      <ba-tree-picker ref="treePicker" :multiple='true' @select-change="selectChange" title="选择" :localdata="listData"
        valueKey="id" textKey="name" childrenKey="childList" />

      <!-- 内容区域列表 -->
      <view class="content-warp">
        <view class="item-warp" v-for="item in itemList" :key="item.id" @click="goPage(item)">
          <view class="txt-warp">
            <view class="fs-28 fw-600 requirement">{{ item.taskName }}</view>
            <!-- <text>{{ item.time }}</text> -->
            <view>
              <text class="fw-600 fs-26"> 积分上限：</text>
              <text>{{ item.pointsCap }}</text>
            </view>
          </view>
          <view class="rows rowsm rowsb mb-30 mt-30">
            <view>
              <text class="fw-600 fs-26"> 实践课程：</text>
              <text>
                <!-- {{ item.practiceType == 1 ? '劳动教育' : item.practiceType == 2 ? '职业素养' : item.practiceType == 3 ?
                '应急安全' : item.practiceType == 4 ? '思政实践' : '创新创业' }} -->
                {{ (practiceType.find(v => v.value == item.practiceType) || {}).name }}
              </text>
            </view>
            <view style="width: 40%;">
              <text class="fw-600 fs-26"> 任务状态：</text>
              <text>{{ taskTab2.find(v => v.value === item.taskStatus).name }}</text>
            </view>
          </view>
          <view class="rows rowsm rowsb mb-30 mt-30">
            <view>
              <text class="fw-600 fs-26"> 发布时间：</text>
              <text>{{ (item.releaseTime || '').slice(0, 16) }}</text>
            </view>
            <view style="width: 40%;" @click.stop="null">
              <uni-tooltip :content="`${item.nickName}(${item.jsNumber})`" placement="top" style="width: 100%;"
                v-if="(item.nickName.length + item.jsNumber.length + 2) > 10 || (item.releaseByName && (item.releaseByName.length + item.releaseJsNumber.length + 2) > 10)">
                <view class="stateEllipsis rows rowsm rowsb">
                  <view class="fw-600 fs-26"> {{ item.taskStatus != '0' ? '发 布 人：' : '创 建 人:' }} </view>
                  <view class="stateEllipsis">
                    {{ item.taskStatus != '0' ? item.releaseByName : item.nickName }}({{ item.taskStatus != '0' ?
                      item.releaseJsNumber : item.jsNumber }})
                  </view>
                </view>
              </uni-tooltip>
              <view v-else>
                <text class="fw-600 fs-26"> {{ item.taskStatus != '0' ? '发 布 人：' : '创 建 人:' }}</text>
                <text class="stateEllipsis">
                  {{ item.taskStatus != '0' ? item.releaseByName : item.nickName }}({{ item.taskStatus != '0' ?
                    item.releaseJsNumber : item.jsNumber }})
                </text>
              </view>
            </view>
          </view>
          <view class="rows rowsm rowsb mb-10">
            <view class="requirement" style="width: 35%;">
              <text class="fw-600 fs-26"> 任务要求：</text>
              <text>{{ item.taskRequire }}</text>
            </view>
            <view @click.stop="completionBtn(item)" class="btn"
              v-if="item.taskStatus != 0 && (permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'practice:user:performanceXy'))">
              完成情况</view>
            <view @click.stop="applicaView(item)" class="btn"
              v-if="item.taskStatus != 0 && item.participationWay == 2 && (permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'practice:user:registration'))">
              报名情况</view>
            <view @click.stop="publishBtn(item)" class="btn"
              v-if="item.taskStatus == 0 && (permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:task:add'))">
              发布</view>
            <view class="btnError" @click.stop="delteBtn(item)"
              v-if="item.taskStatus == 0 && (permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:task:add'))">
              删除</view>
            <view class="btnWrting" @click.stop="withdrawBtn(item)"
              v-if="item.taskStatus != 0 && (permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:task:edit'))">
              撤回</view>
          </view>
        </view>
        <view v-if="itemList.length == 0" class="notYet">
          暂无数据
        </view>
      </view>

    </view>
  </view>
</template>

<script>
import { Base64 } from 'js-base64';
import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
export default {
  data() {
    return {
      items: ['指定学生参与', '学生自选报名'],
      current: 0,
      styleType: 'line',
      value: '',
      active: 0,
      active2: 0,
      active3: 0,
      title: '',
      range: '',
      total: 0,
      practiceType: [
        { name: '全部', value: '' },
      ],
      taskTab: [
        { name: '全部', value: 0 },
        { name: '未发布', value: 1 },
        { name: '未开始', value: 2 },
        { name: '进行中', value: 3 },
        { name: '已结束', value: 4 }
      ],
      taskTab2: [
        { name: '未发布', value: 0 },
        { name: '未开始', value: 1 },
        { name: '进行中', value: 2 },
        { name: '已结束', value: 3 }
      ],
      taskType: [
        { name: '全部', value: 0 },
        { name: '必填任务', value: 1 },
        { name: '选填任务', value: 2 },
      ],
      completionStatus: [
        { name: '全部', value: 0 },
        { name: '已完成', value: 1 },
        { name: '审批中', value: 2 },
        { name: '已驳回', value: 3 },
      ],
      itemList: [],
      limit: {
        pageNum: 1,
        pageSize: 10,
      },
      proxyIndex: null,
      proxyList: [],
      prozyAddList: [],
      prozyAddIndex: null,
      probjAddList: [],
      probjAddIndex: null,
      pronjAddList: [],
      faceXy: '',
      faceZy: '',
      faceBj: '',
      faceNj: '',
      taskName: null,
      permissList: [],
      selectorList: [],
      classItem: null,
      listData: [],
      xyIdList: [],
      zyIdList: [],
      bjIdList: [],
      permissions: []
    };
  },
  components: {
    baTreePicker
  },
  onShow(e) {
    this.itemList = [];
    this.limit.pageNum = 1;
    this.getList();
  },
  onLoad() {
    if (uni.getStorageSync('flag') == 'teacher') {
      this.$tools.axiosFromToken('POST', 'sysUser/getById', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        let getAllInfo = { ...res.data, user: JSON.parse(Base64.decode(res.data.user)) }
        uni.setStorageSync('getInfo', getAllInfo);
        this.permissions = res.data.permissions.flat() || [];
      })
    }

    this.getAllBj();
    // this.getSelectorListTaks();
    this.getTypeCongfigList();

    // this.permissList = uni.getStorageSync('getInfo').practiceTypes;
    // this.permissions = uni.getStorageSync('getInfo').permissions.flat() || [];
    // const typeMap = {
    //   1: { name: '劳动教育', value: 1 },
    //   2: { name: '职业素养', value: 2 },
    //   3: { name: '应急安全', value: 3 },
    //   4: { name: '思政实践', value: 4 },
    //   5: { name: '创新创业', value: 5 }
    // };

    // this.permissList.forEach(v => {
    //   if (typeMap[v]) {
    //     this.practiceType.push(typeMap[v]);
    //   }
    // });
  },
  watch: {
    taskName(newId) {
      this.limit.pageNum = 1;
      this.getList();
    }
  },
  // 下拉到底部后加载新数据
  onReachBottom() {
    if (this.itemList.length < this.total) {
      this.limit.pageNum++;
      this.getList();
    }
  },
  created() {
    // this.getListProxy();
    // this.getListProzy();
    // this.getListProbj();
    // this.getListPronj();
  },
  methods: {
    getTypeCongfigList() {
      this.$tools.axiosFromToken('GET', 'project/practice/type/config/list?pageNum=1&pageSize=50', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        res.rows.forEach(item => {
          this.practiceType.push({ name: item.name, value: item.id })
        })
      })
    },
    getAllBj() {
      this.$tools.axiosFromToken('POST', 'prouser/getBj', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.listData = [];
        this.listData = res.data;
      })
    },
    onClickItem(e) {
      this.current = e.currentIndex;
      this.limit.pageNum = 1;
      this.getList();
    },
    // 显示选择器
    showPicker() {
      this.$nextTick(() => {
        this.$refs.treePicker._show();
      })
    },
    //监听选择（ids为数组）
    selectChange(ids, names) {
      this.classItem = names;
      this.xyIdList = [];
      this.zyIdList = [];
      this.bjIdList = [];
      ids.forEach(v => {
        if (v.type == 'xy') {
          this.xyIdList.push(v.id)
        }
        if (v.type == 'zy') {
          this.zyIdList.push(v.id)
        }
        if (v.type == 'bj') {
          this.bjIdList.push(v.id)
        }
      })
      this.handelType();
    },
    getSelectorListTaks() {
      this.$tools.axiosFromToken('GET', 'project/task/selectorForList?taskNameSort=desc', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        res.rows.forEach(item => {
          this.selectorList.push({ text: item.taskName, value: item.taskName })
        })
      })
    },
    handelTab(index) {
      this.limit.pageNum = 1;
      this.active = this.taskTab[index].value;
      this.getList();
    },
    handelType() {
      this.limit.pageNum = 1;
      this.getList();
    },
    handelPracticeType(index) {
      this.limit.pageNum = 1;
      this.active3 = this.practiceType[index].value;
      this.getList();
    },
    changeProxy(e) {
      this.proxyIndex = e.detail.value;
      this.faceXy = this.proxyList[e.detail.value].id;
    },
    changeProzy(e) {
      this.prozyAddIndex = e.detail.value;
      this.faceZy = this.prozyAddList[e.detail.value].id;
    },
    changeProbj(e) {
      this.probjAddIndex = e.detail.value;
      this.faceBj = this.probjAddList[e.detail.value].id;
    },
    changeTime(e) {
      this.limit.pageNum = 1;
      this.range = e;
      this.getList();
    },
    // 查询学院
    getListProxy() {
      this.$tools.axiosFromToken('GET', 'project/proxy/listTotal', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.proxyList = res.rows;
        // res.rows.forEach(item => {
        //   this.proxyList.push({ text: item.name, value: item.id })
        // })
      })
    },
    // 查询专业
    getListProzy() {
      this.$tools.axiosFromToken('GET', 'project/prozy/listTotal', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.prozyAddList = res.rows
        // res.rows.forEach(item => {
        //   this.prozyAddList.push({ text: item.name, value: item.id })
        // })
      })
    },
    // 查询班级
    getListProbj() {
      this.$tools.axiosFromToken('GET', 'project/probj/listTotal', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.probjAddList = res.rows;
        // res.rows.forEach(item => {
        //   this.probjAddList.push({ text: item.name, value: item.id })
        // })
      })
    },
    // 查询年级
    getListPronj() {
      this.$tools.axiosFromToken('GET', 'project/class/selectorForList', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        res.rows.forEach(item => {
          this.pronjAddList.push({ text: item.name, value: item.name })
        })
      })
    },
    goPage(item) {
      if (item.taskStatus == 0) {
        this.$tools.goNext(`/teacher/practiceTask/addPractice?id=${item.id}`)
      } else {
        this.$tools.goNext(`/teacher/practiceTask/practiceDetail?id=${item.id}`)
      }
    },
    completionBtn(item) {
      this.$tools.goNext(`/teacher/practiceTask/taskDetail?item=${JSON.stringify(item)}`)
    },
    applicaView(item) {
      this.$tools.goNext(`/teacher/practiceTask/applicaCompletion?item=${JSON.stringify(item)}`)
    },
    getDate() {
      const now = new Date();

      const year = now.getFullYear();  // 获取年份
      const month = String(now.getMonth() + 1).padStart(2, '0');  // 获取月份，月从 0 开始，所以需要加 1，使用 padStart 补充零
      const day = String(now.getDate()).padStart(2, '0');  // 获取日期，使用 padStart 补充零

      const hours = String(now.getHours()).padStart(2, '0');  // 获取小时，补充零
      const minutes = String(now.getMinutes()).padStart(2, '0');  // 获取分钟，补充零
      const seconds = String(now.getSeconds()).padStart(2, '0');  // 获取秒数，补充零

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    publishBtn(item) {
      this.$tools.axiosFromToken('PUT', 'project/task', { ...item, taskStatus: 1, releaseTime: this.getDate() }, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        setTimeout(() => {
          this.$tools.showtt('发布成功');
        }, 200);
        this.limit.pageNum = 1;
        this.getList();
      })
    },
    getList() {
      const data = {
        practiceType: this.active3 > 0 ? this.active3 : '',
        taskName: this.taskName,
        taskStatus: this.active === 0 ? '' : this.active - 1,
        isH5: 1,
        xyIdList: this.xyIdList,
        zyIdList: this.zyIdList,
        bjIdList: this.bjIdList,
        participationWay: this.current + 1,
        startTime: this.range.length > 0 ? this.range[0] + " 00:00:00" : null,
        endTime: this.range.length > 0 ? this.range[1] + " 23:59:59" : null,
      };
      this.$tools.axiosFromToken('GET', `project/task/list?pageNum=${this.limit.pageNum}&pageSize=${this.limit.pageSize}`, data, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.total = res.total;
        if (this.limit.pageNum == 1) {
          this.itemList = [];
          this.itemList = res.rows;
        } else {
          this.itemList = [...this.itemList, ...res.rows];
        }
      })
    },
    addTask() {
      this.$tools.goNext(`/teacher/practiceTask/addPractice`)
    },
    delteBtn(row) {
      uni.showModal({
        title: '确认删除',
        content: `是否确认删除"${row.taskName}"任务的数据项？`,
        success: (res) => {
          if (res.confirm) {
            this.$tools.axiosFromToken('DELETE', `project/task/${row.id}`, {}, '加载中').then(resMsg => {
              if (resMsg.code != 200) return this.$tools.showtt(resMsg.msg);
              setTimeout(() => {
                this.$tools.showtt('删除成功');
              }, 200);
              this.limit.pageNum = 1;
              this.itemList = [];
              this.getList();
            })
          } else if (res.cancel) {
            // 用户点击了“取消”
            console.log('取消删除');
          }
        }
      });
    },
    withdrawBtn(row) {
      uni.showModal({
        title: '确认撤回',
        content: `是否撤回"${row.taskName}"的实践任务,撤回后学生无法查看任务`,
        success: (res) => {
          if (res.confirm) {
            this.$tools.axiosFromToken('PUT', 'project/task', { ...row, taskStatus: 0 }, '加载中').then(res => {
              this.$tools.showtt(res.msg);
              if (res.code != 200) return
              setTimeout(() => {
                this.$tools.showtt('撤回成功');
              }, 200);
              this.limit.pageNum = 1;
              this.itemList = [];
              this.getList();
            })
          } else if (res.cancel) {
            // 用户点击了“取消”
            console.log('取消删除');
          }
        }
      });
    },
    handelReset() {
      this.limit.pageNum = 1;
      this.taskName = '';
      this.range = [];
      this.active = 0;
      this.active3 = 0;
      this.xyIdList = null;
      this.zyIdList = null;
      this.bjIdList = null;
      this.getAllBj();
      this.getList();
    },
  }
}
</script>

<style lang="scss">
page {
  background-color: #f4f5f7;

  ::v-deep .u-input {
    padding: 3px !important;
  }

  ::v-deep .uni-date__x-input {
    height: auto !important;
    padding: 5px !important;
  }
}

::v-deep .uni-flex-item {
  display: flex;
  align-items: center !important;
}

.add {
  width: 85px;
  height: 34px;
  text-align: center;
  line-height: 34px;
  background: #658dec;
  color: #fff;
  border-radius: 34px;
  font-size: 15px;
}

.title {
  color: #333;
  font-size: 28rpx;
  font-weight: 500;
  // width: 300rpx;
  white-space: nowrap;
}

.title2 {
  color: #333;
  font-size: 28rpx;
  width: 120rpx;
}

.btnWarp {
  width: 140px;
  height: 49px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .u-button.data-v-2bf0e569 {
    height: 30px !important;
    margin-left: 10px;
  }

}

.overFlow {
  width: 40%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.content-warp {
  color: #333;
  font-size: 24rpx;

  .item-warp {
    padding: 24rpx;
    width: 100%;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 30rpx;

    .requirement {
      width: 60%;
      // 溢出显示省略号
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }

    .btn {
      font-size: 24rpx;
      border: 1px solid #5ac725;
      padding: 5px 10px;
      border-radius: 20px;
      color: #5ac725;
      background: #fff;
    }

    .btnError {
      font-size: 26rpx;
      border: 1px solid #ff0000;
      padding: 5px 10px;
      border-radius: 20px;
      color: #ff0000;
      background: #fff;
    }

    .btnWrting {
      font-size: 26rpx;
      border: 1px solid #ff5500;
      padding: 5px 10px;
      border-radius: 20px;
      color: #ff5500;
      background: #fff;
    }
  }

  .txt-warp {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .title {
      font-size: 30rpx;
      font-weight: bold;
    }
  }
}

::v-deep .uni-stat__select {
  width: 75%;
  padding: 0 !important;

  view {
    width: 100%;
  }
}

.stateEllipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.notYet {
  margin-top: 50rpx;
  width: 100%;
  text-align: center;
  font-weight: 0 !important;
  font-size: 42rpx;
}

.example-body {
  padding: 10px;
}

.scroll-view {
  /* #ifndef APP-NVUE */
  width: 100%;
  height: 100%;
  /* #endif */
  flex: 1
}
</style>
